import React from 'react';
import { Table, Button, Popconfirm, Tooltip } from 'antd';
import Position from './Position';
import styles from './index.less';

let rowKey = 0;
const AddTable = ({ onChange, value }) => {
    const handleDelete = key => {
        const rest = value.filter(item => item.key !== key);
        if (onChange) {
            onChange([...rest]);
        }
    };
    const handleAdd = () => {
        rowKey += 1;
        onChange([...value, { key: rowKey }]);
    };
    const textWidth = record => (record ? '145px' : '130px');
    const columns = [
        {
            title: '职位名称',
            key: 'Name',
            render: record => <Position onChange={onChange} value={value} recordKey={record.key} />
        },
        {
            title: '操作',
            key: 'action',
            render: record => (
                <span>
                    {value.length > 1 && !record.isRelationToEmployee ? (
                        <Popconfirm title="确定删除?" onConfirm={() => handleDelete(record.key)}>
                            <a>删除</a>
                        </Popconfirm>
                    ) : (
                        <Tooltip
                            placement="top"
                            overlayStyle={{ width: textWidth(record.isRelationToEmployee) }}
                            title={record.isRelationToEmployee ? '该职位已有员工入职' : '至少关联一个职位'}
                        >
                            <span style={{ opacity: '0.45', color: '#FFA22D' }}>删除</span>
                        </Tooltip>
                    )}
                </span>
            )
        }
    ];
    return (
        <div className={`${styles.show} postContainer`}>
            <Table
                rowClassName={() => 'add-row'}
                dataSource={value}
                pagination={false}
                bordered
                columns={columns}
                style={{ maxHeight: 500, overflow: 'auto', marginTop: '-8px' }}
            />
            <Button
                onClick={() => {
                    handleAdd();
                }}
                type="primary"
                style={{ marginTop: '10px' }}
            >
                添加
            </Button>
        </div>
    );
};

export default AddTable;
